


package monitor
/*
#cgo CFLAGS: -I./
#cgo LDFLAGS: -L./ -lmp3
#include "libmad_play.h"
*/
import "C" //这里可看作封装的伪包C, 这条语句要紧挨着上面的注释块，不可在它俩之间间隔空行！



import (
	"fmt"
    "time"
    "net"
    "os"
    "unsafe"
)
//00 00
//0A 19 0e //取pgid为0x190c的节目
//0B 00 00 //停止
//01 00 00 //保持心跳

var load = []byte{0, 0}
var a [3]int
type Bconn struct {
	conn 		net.Conn
	ch 			chan []byte
	established bool
	lcnt 		int
	speed 		int
	lastspeed 	int
	lf *DataFile
}

func (b *Bconn)HandleTcpRec(a []byte) {
	//fmt.Println("tcp rec", len(a))
	b.lf.Mp3Write(a)
}


func (b *Bconn) recv() {
	var buf [1460]byte
	C.libmad_media_start(2, 48000)   
    for {
    	//conn.SetReadDeadline(time.Now().Add(10 * time.Second))
	    n, err := b.conn.Read(buf[0:])
	    if err != nil {
	    	break
	    }
	    a := buf[:n]
		var pOutData *C.uchar
		var pOutDataLen C.uint
		pOutData = (*C.uchar)(unsafe.Pointer(&buf[0]))
		pOutDataLen = C.uint(len(a))
		C.mp3_buf_write(pOutData, pOutDataLen)
		
		b.lf.Mp3Write(a)
		IdbgPg(4, "pg rec ", n, "bytes")
	    b.lcnt += n
    }
     C.libmad_media_stop_sync()
}

func (b *Bconn) sendv(syn chan struct{}) {
	var	cmdHeartTick= [3]byte{0x01, 0x00, 0x00}
	hearttick := time.Tick(3000 * time.Millisecond)
	tcnt1m := time.Tick(120 * time.Second)
    for {
        select {
        case _, ok := <-syn:
            if !ok {
            	return
            }
        case msg, ok := <-b.ch:
        	if ok {
				n, err := b.conn.Write(msg)
	        	if err != nil {
					return
	        	}
	        	IdbgSend(2, "send pg", n , msg)
            }
        case <-hearttick: 
        	_, err := b.conn.Write(cmdHeartTick[:]) /*heartick*/
        	if err != nil {
				return
	        }
        	b.speed = (b.lcnt + 200)/(3*1024)
        	b.lcnt = 0
        	off := b.speed - b.lastspeed
        	if off >= 3 || off <= -3 {
				b.lf.WriteLogf("节目流量变化：%dKB/s -> %dKB/s\r\n", b.lastspeed, b.speed)	
        	}
        	b.lastspeed= b.speed
        case <-tcnt1m: 
        	if b.speed > 0 {
				b.lf.WriteLogf("节目流量：%dKB/s\r\n", b.speed)	
				//fmt.Printf("节目流量：%dKB/s\r\n", b.speed)	
        	}
        }
    }
}

func (b *Bconn) RunPg(remoteIp string, ch chan []byte, lf *DataFile) {
	addr, err := net.ResolveTCPAddr("tcp4", remoteIp)
	if err != nil {
        fmt.Println("ResolveTCPAddr error:", err.Error())
        os.Exit(1)
    }
    C.libmad_init()
    b.ch = ch
    b.lf = lf
    for {
        b.conn, err = net.DialTCP("tcp", nil, addr)
        if err == nil {
            defer b.conn.Close()
			syn := make(chan struct{})
		    defer close(syn)
		    go b.sendv(syn)
		    b.ch <- load
			b.established = true
		    b.lf.WriteLogln("pg 网络连接成功", addr)
            b.recv()
            b.lf.WriteLogln("pg 网络断开")
            b.established = false
            
        }
        time.Sleep(2 * time.Second)
    }
}










